package cn.com.dhcc.turbo.service.rmi;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.handler.remotehandler.socket.ICallBack;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.SUCCESSFAIL;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.turbo.entity.exch.CmData;
import cn.com.dhcc.turbo.entity.exch.CrossNetTmpCmData;
import cn.com.dhcc.turbo.entity.exch.QueueMsgWrapper;
import cn.com.dhcc.turbo.entity.exch.QueueMsgWrapper.ExchageLifecycle;
import cn.com.dhcc.turbo.entity.exch.RecvCmData;
import cn.com.dhcc.turbo.entity.exch.SendCmData;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.registry.sync.SyncCallBack;
import cn.com.dhcc.turbo.service.transport.TransportPipeline;

@Component(AppIocBean.RMI_TRANSPORT_PIPELINE_BEAN)
public class RmiTransportPipeline implements TransportPipeline{
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.R);
	@Autowired
	private NodeInfoService nodeInfoService;
	@Autowired
	private RmiSendMessageClient rmiSendMessageClient;
	
	private Status send(String toCode,QueueMsgWrapper queueMsgWrapper) throws Exception{
		 final Status status=Status.getInstance();
		NodeInfo nodeInfo=nodeInfoService.getNodeByNodeCode(toCode);
		String[] ip_port = nodeInfo.getInstallUrl().split(":");
		String ip = ip_port[0];
		int port = Integer.parseInt(ip_port[1]);
		
		rmiSendMessageClient.sendData(ip, port, queueMsgWrapper, new ICallBack() {
			@Override
			public void recevieCallBackData(Object callBackData) throws NiceException {
				SyncCallBack callBack = (SyncCallBack)callBackData;
				SUCCESSFAIL result = callBack.getResult();
				
				//失败
				if(result.getStatus().equals(SUCCESSFAIL.SUCCESS.getStatus())){
				   status.setMsg(callBack.getMsg());
				   status.setSuccess(true);
				}else{
					status.setMsg(callBack.getMsg());
					status.setSuccess(false);
				}
				
			}
			@Override
			public void onException(Throwable cause) throws NiceException {
				status.setSuccess(false);
				status.setMsg(cause.getMessage());
			}
		});
		return status;
	}
	
	@Override
	public Status sendData(Object data, String fromCode, String toCode,
			ExchageLifecycle exchageLifecycle) {
		logger.info("RmiTransportPipeline >>>>>> sending data[" + data + "]");
		Status status = Status.getInstance();
		String msg = "";
		try {
			CmData cmData=null;
			if (data instanceof SendCmData) {
				cmData=(SendCmData)data;
			}else if(data instanceof RecvCmData){
				cmData=(RecvCmData)data;
			}else if(data instanceof CrossNetTmpCmData){
				cmData=(CrossNetTmpCmData)data;
			}else{
				logger.info("RmiTransportPipeline >>>>>> sending data[" + data + "]不能被识别");
				msg = "数据发送至传输管道[RmiTransportPipeline],参数data不能被识别";
				status.setSuccess(false);
				status.setMsg(msg);
				return status;
			}
			
			String filePath = AppConst.CMDATA_STORED_DIR + File.separator + cmData.getPayload();
			File file = new File(filePath);
			if (!file.exists()) {
				msg = "数据发送至传输管道[RmiTransportPipeline]失败：数据报文文件[" + filePath + "]找不到";
				status.setSuccess(false);
				status.setMsg(msg);
				return status;
			}
			String payloadContent = FileUtils.readFileToString(file,AppConst.CHARSET_UTF8);
			cmData.setPayloadContent(payloadContent);

			//封装消息信息
			String queueName = "SQ_" + fromCode.toUpperCase() + "_TO_"+ toCode.toUpperCase() + "_CM_DATA";
			QueueMsgWrapper queueMsgWrapper = new QueueMsgWrapper();
			queueMsgWrapper.setQueueName(queueName);
			queueMsgWrapper.setExchageLifecycle(exchageLifecycle);
			queueMsgWrapper.setData(cmData);
			
			status=this.send(toCode, queueMsgWrapper);
			if (status.isSuccess()) {
				msg = "远程RMI接收成功：[RmiTransportPipeline]" + status.getMsg();
				status.setSuccess(true);
				status.setMsg(msg);
			} else {
				msg = "远程RMI接收失败：[RmiTransportPipeline]:" + status.getMsg();
				status.setSuccess(false);
				status.setMsg(msg);
			}
			return status;
		} catch (Exception e) {
			msg = "数据发送至传输管道[RmiTransportPipeline]出现异常:" + e.fillInStackTrace();
			status.setSuccess(false);
			status.setMsg(msg);
			logger.error(msg, e);
			return status;
		}
	}

	@Override
	public Status sendLog(Object data, String fromCode, String toCode,
			ExchageLifecycle exchageLifecycle) {
		logger.info("RmiTransportPipeline >>>>>> sending data[" + data + "]");
		Status status = Status.getInstance();
		String msg = "";
		try {
			CmData cmData=null;
			if (data instanceof SendCmData) {
				cmData=(SendCmData)data;
			}else if(data instanceof RecvCmData){
				cmData=(RecvCmData)data;
			}else if(data instanceof CrossNetTmpCmData){
				cmData=(CrossNetTmpCmData)data;
			}else{
				logger.info("RmiTransportPipeline >>>>>> sending data[" + data + "]不能被识别");
				msg = "数据发送至传输管道[RmiTransportPipeline],参数data不能被识别";
				status.setSuccess(false);
				status.setMsg(msg);
				return status;
			}
			
			String filePath = AppConst.CMDATA_STORED_DIR + File.separator + cmData.getPayload();
			File file = new File(filePath);
			if (!file.exists()) {
				msg = "数据发送至传输管道[RmiTransportPipeline]失败：数据报文文件[" + filePath + "]找不到";
				status.setSuccess(false);
				status.setMsg(msg);
				return status;
			}
			String payloadContent = FileUtils.readFileToString(file);
			cmData.setPayloadContent(payloadContent);

			//调用Rmi接口
			//TODO by t根据toCode查找接口
			String queueName  = "SQ_" + fromCode.toUpperCase() + "_TO_"+ toCode.toUpperCase()+ "_CM_DATA_LOG";
			QueueMsgWrapper queueMsgWrapper = new QueueMsgWrapper();
			queueMsgWrapper.setQueueName(queueName);
			queueMsgWrapper.setExchageLifecycle(exchageLifecycle);
			queueMsgWrapper.setData(cmData);
			
			status=this.send(toCode, queueMsgWrapper);
			
			if (status.isSuccess()) {
				msg = "数据发送至传输管道成功：[RmiTransportPipeline]" + status.getMsg();
				status.setSuccess(true);
				status.setMsg(msg);
			} else {
				msg = "数据发送至传输管道失败：[RmiTransportPipeline]:" + status.getMsg();
				status.setSuccess(false);
				status.setMsg(msg);
			}
			return status;
		} catch (Exception e) {
			msg = "数据发送至传输管道[RmiTransportPipeline]出现异常:" + e.fillInStackTrace();
			status.setSuccess(false);
			status.setMsg(msg);
			logger.error(msg, e);
			return status;
		}
	}

}
